package com.winchain.chainbill.receivables.biz.impt.rx;

import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.command.ChainBase;
import com.shell.framework.command.CommandContext;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.winchain.chainbill.receivables.base.po.ArRecord;
import com.winchain.chainbill.receivables.biz.impt.cmd.ReceivablesMoveCmd;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ReceivablesImptRevRjctSubscriber extends OnErrorNotImplementedSubscriber<BatchReceivablesRevEvent> {
	private final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private ReceivablesMoveCmd receivablesMoveCmd;

	public void onApplicationEvent(final BatchReceivablesRevEvent t) {
		List<ArRecord> records = t.getRecs();
		BatchReceivablesStats stats = t.getStats();
		for (final ArRecord record : records) {
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						CommandContext<ArRecord> context = new CommandContext();
						context.setSource(record);
						context.setValue("Operation", t.getOperation());
						context.setValue("TimeoutOperation", t.getTimeoutOperation());

						ChainBase<ArRecord> crb = new ChainBase();
						crb.add(ReceivablesImptRevRjctSubscriber.this.receivablesMoveCmd);
						crb.execute(context);
					}
				}, new int[0]);

				stats.addPassedRecord(record);
			} catch (Exception e) {
				e.printStackTrace();
				this.logger.error("ArRecord Impt Rev Rjct error!", e);
				stats.addAbnormalRecord(record);
				stats.addAbnormalMsg(e.getMessage());
			}
		}
	}
}
